package com.lin.util;

import com.lin.entity.SecurityUser;
import com.lin.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class JwtUtil {

    public static final String TOKEN_HEADER = "Authorization";
    public static final String TOKEN_PREFIX = "Bearer ";
    public static final long EXPIRITION = 1000 * 24 * 60 * 60 * 7;
    public static final String APPSECRET_KEY = "PW5XsKxeaYDaSXW6";

    public static String generateJwt(SecurityUser user) {
        if (user.getUid() == null || user.getUsername() == null) {
            return null;
        }

        Map<String, Object> map = new HashMap<>();
        map.put(User.UID, user.getUid());
        map.put(User.USERNAME, user.getUsername());
        map.put(User.ROLE, user.getStrRole());
        String token = Jwts
                .builder()
                .setClaims(map)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRITION))
                .setSubject("client")
                .setIssuer("com.lin")
                .signWith(SignatureAlgorithm.HS512, APPSECRET_KEY).compact();
        return token;
    }

    public static SecurityUser getSecurityUserFromToken(String token) {
        try {
            Claims claims = getClaimsFromToken(token);
            if (claims == null) return null;
            SecurityUser user = new SecurityUser(new User((Integer) claims.get(User.UID), (String) claims.get(User.USERNAME), "", (String) claims.get(User.ROLE)));
            return user;
        } catch (Exception e) {
            return null;
        }
    }

    private static Claims getClaimsFromToken(String token) {
        if (token == null) return null;
        Claims claims;
        try {
            claims = Jwts.parser()
                    .setSigningKey(APPSECRET_KEY)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            claims = null;
        }
        return claims;
    }


    public static String getUsernameFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        if (claims == null) return null;
        return (String) claims.get(User.USERNAME);
    }

    public static Integer getUidFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        if (claims == null) return null;
        return (Integer) claims.get(User.UID);
    }

    public static List<GrantedAuthority> getUserRole(String token) {
        Claims claims = getClaimsFromToken(token);
        if (claims == null) return null;
        return AuthorityUtils.commaSeparatedStringToAuthorityList(String.valueOf(claims.get(User.ROLE)));
    }

}


